package com.company.test30;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by v on 16-12-5.
 */
public class Test3004Server extends JApplet implements Runnable{
    private JTextArea area=new JTextArea();
    private JButton jbt=new JButton("Stop");
    ServerSocket serverSocket;

    ExecutorService service= Executors.newCachedThreadPool();

    //记录访问次数
    Integer count;

    //主线程
    Thread thread;

    //记录文件
    RandomAccessFile raf;

    public Test3004Server(){
        setLayout(new BorderLayout());
        add(jbt,BorderLayout.SOUTH);
        add(new JScrollPane(area),BorderLayout.CENTER);

        jbt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                while (!service.isTerminated()){
                    service.shutdown();
                    try{
                        Thread.sleep(10);
                    }catch (InterruptedException ex){
                        ex.printStackTrace();
                    }
                    stop();
                    destroy();
                    System.exit(0);
                }
            }
        });

        try{
            serverSocket=new ServerSocket(8000);
            raf=new RandomAccessFile("count.dat","rw");

            if(raf.length()==0){
                count=0;
            }else{
                count=raf.readInt();
            }

            thread=new Thread(this);
            thread.start();
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        try{
            while (true){
                Socket socket=serverSocket.accept();
                service.execute(new Thread(new Visit(socket)));
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    public class Visit implements Runnable{
        private Socket socket;
        public Visit(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            synchronized (count){
                count++;
                try{
                    DataOutputStream output=new
                            DataOutputStream(socket.getOutputStream());
                    output.writeInt(count);
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        try{
            raf.seek(0);
            raf.writeInt(count);
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
